import React, { useState, useRef } from 'react';
import { Button, Input, Table, Form, Space, Pagination, Modal, message, Select } from 'antd';
import { PlusOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';

const { Option } = Select;

const mockData = [
  { key: 1, name: '杭州公燃科技有限公司', billNo: 'SF-2021-07-14-00008', type: '电费', usage: 443, price: 0.53, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 2, name: '杭州鹏云科技有限公司', billNo: 'WYF-2021-07-14-00006', type: '电费', usage: 678, price: 0.53, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 3, name: '杭州彩凝科技有限公司', billNo: 'DF-2021-07-14-00006', type: '电费', usage: 540, price: 0.53, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 4, name: '南京可达职悦乐有限公司', billNo: 'DF-2021-07-14-00004', type: '物业费', usage: 109, price: 2.3, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 5, name: '杭州超彩科技有限公司', billNo: 'DF-2021-07-13-00020', type: '物业费', usage: 200, price: 2.3, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 6, name: '杭州屹辰西沃科技有限公司', billNo: 'DF-2021-07-13-00019', type: '燃气费', usage: 103, price: 3.1, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 7, name: '喵兜呗（杭州）科技有限公司', billNo: 'DF-2021-07-13-00015', type: '燃气费', usage: 189, price: 3.1, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 8, name: '杭州依熙商务服务有限公司', billNo: 'DF-2021-07-13-00002', type: '水费', usage: 45, price: 2.5, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 9, name: '杭州润淼投资管理有限公司', billNo: 'DF-2021-07-09-00002', type: '水费', usage: 60, price: 2.5, billDate: '2022-01-23', payDate: '2022-01-23' },
  { key: 10, name: '杭州标钧工程机械科技有限公司', billNo: 'DF-2021-07-16-00002', type: '水费', usage: 80, price: 2.5, billDate: '2022-01-23', payDate: '2022-01-23' },
];

export default function TenantBill() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState(mockData);
  const allDataRef = useRef(mockData); // 保存所有数据
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailData, setDetailData] = useState(null);

  React.useEffect(() => {
    if (location.state && location.state.newTenantBill) {
      setData(prevData => [location.state.newTenantBill, ...prevData]);
      allDataRef.current = [location.state.newTenantBill, ...allDataRef.current];
    }
    // eslint-disable-next-line
  }, [location.state]);

  // 查询功能
  const handleSearch = async () => {
    const values = await form.getFieldsValue();
    const name = values.name?.trim();
    if (!name) {
      setData(allDataRef.current);
      return;
    }
    setData(allDataRef.current.filter(item => item.name.includes(name)));
  };

  // 重置功能
  const handleReset = () => {
    form.resetFields();
    setData(allDataRef.current);
  };

  const showDetail = (record) => {
    setDetailData(record);
    setDetailVisible(true);
  };

  const columns = [
    { title: '租户名称', dataIndex: 'name', align: 'center' },
    { title: '账单编号', dataIndex: 'billNo', align: 'center' },
    { title: '账单类型', dataIndex: 'type', align: 'center' },
    { title: '使用量', dataIndex: 'usage', align: 'center' },
    { title: '单价', dataIndex: 'price', align: 'center' },
    { title: '出账时间', dataIndex: 'billDate', align: 'center' },
    { title: '缴费时间', dataIndex: 'payDate', align: 'center' },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => showDetail(record)}>详情</Button>
          <Button type="link" danger onClick={() => handleDelete(record.key)}>删除</Button>
        </Space>
      ),
    },
  ];

  const handleDelete = (key) => {
    Modal.confirm({
      title: '确认删除该账单吗？',
      onOk: () => setData(data.filter(item => item.key !== key)),
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的账单');
      return;
    }
    Modal.confirm({
      title: '确认批量删除所选账单吗？',
      onOk: () => {
        setData(data.filter(item => !selectedRowKeys.includes(item.key)));
        setSelectedRowKeys([]);
      },
    });
  };

  return (
    <div style={{ background: '#fff', minHeight: '100vh', padding: 24 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24, justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button type="default" icon={<ArrowLeftOutlined />} onClick={() => navigate('/dashboard/enterprise')} style={{ marginRight: 16 }}>
            返回
          </Button>
          <div style={{ width: 12, height: 24, background: '#4880ff', borderRadius: 2, marginRight: 12 }} />
          <span style={{ fontWeight: 700, fontSize: 22 }}>租户账单管理</span>
        </div>
        <div>
          <Button type="primary" style={{ background: '#21a1ff', border: 'none', marginRight: 16, fontWeight: 700 }} onClick={() => navigate('/tenant-bill/create')}>新增</Button>
          <Button style={{ background: '#ffc107', color: '#fff', border: 'none', fontWeight: 700 }} onClick={handleBatchDelete}>批量删除</Button>
        </div>
      </div>
      <div style={{ background: '#fff', borderRadius: 8, border: '1px solid #e5e6eb', padding: 24, marginBottom: 24 }}>
        <Form layout="inline" form={form} style={{ marginBottom: 16, flexWrap: 'wrap', display: 'flex' }}>
          <Form.Item label="租户名称:" name="name">
            <Input placeholder="请输入租户名称" style={{ width: 300 }} />
          </Form.Item>
          <Form.Item label="所属楼宇:" name="building">
            <Select placeholder="请选择" style={{ width: 200 }} allowClear></Select>
          </Form.Item>
          <Form.Item label="房间名称:" name="room">
            <Input placeholder="请输入房间名称" style={{ width: 300 }} />
          </Form.Item>
          <Form.Item label="账单类型:" name="type">
            <Select placeholder="请选择" style={{ width: 200 }} allowClear></Select>
          </Form.Item>
          <Form.Item label="出账时间:" name="billDate">
            <Input placeholder="请输入出账时间" style={{ width: 300 }} />
          </Form.Item>
          <Form.Item label="缴费时间:" name="payDate">
            <Input placeholder="请输入缴费时间" style={{ width: 300 }} />
          </Form.Item>
          <Button type="primary" style={{ marginLeft: 16 }} onClick={handleSearch}>查询</Button>
          <Button style={{ marginLeft: 16 }} onClick={handleReset}>重置</Button>
        </Form>
        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          columns={columns}
          dataSource={data}
          pagination={false}
          bordered
          style={{ background: '#fff' }}
        />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 24 }}>
          <span>共 100 条</span>
          <Pagination
            total={100}
            showSizeChanger
            showQuickJumper
            pageSizeOptions={[10, 20, 50]}
            defaultPageSize={10}
            style={{ marginRight: 16 }}
          />
          <span>
            到第 <Input style={{ width: 50, margin: '0 8px' }} size="small" /> 页
            <Button size="small">确定</Button>
          </span>
        </div>
      </div>
      <Modal
        open={detailVisible}
        title="账单详情"
        footer={null}
        onCancel={() => setDetailVisible(false)}
        width={600}
      >
        {detailData && (
          <div style={{ padding: 12 }}>
            <div style={{ marginBottom: 12 }}><b>租户名称：</b>{detailData.name}</div>
            <div style={{ marginBottom: 12 }}><b>账单编号：</b>{detailData.billNo}</div>
            <div style={{ marginBottom: 12 }}><b>账单类型：</b>{detailData.type}</div>
            <div style={{ marginBottom: 12 }}><b>使用量：</b>{detailData.usage}</div>
            <div style={{ marginBottom: 12 }}><b>单价：</b>{detailData.price}</div>
            <div style={{ marginBottom: 12 }}><b>出账时间：</b>{detailData.billDate}</div>
            <div style={{ marginBottom: 12 }}><b>缴费时间：</b>{detailData.payDate}</div>
          </div>
        )}
      </Modal>
    </div>
  );
} 